using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace PayPlat.Framework.Uitility
{
    public class KindeditorHelper
    {
        private KindeditorModel model ;

        public KindeditorHelper(KindeditorModel km)
        {
            model = km ;
        }

        public string GetLoadJs()
        {
            //< script src = '{0}/plugins/code/prettify.js' ></ script >
            //    < link rel = 'stylesheet' href = '{0}/plugins/code/prettify.css' />
            return string.Format(@"<link rel='stylesheet' href='{0}/themes/default/default.css'/>      
                     <script charset='utf-8' src='{0}/kindeditor-all.js'></script>
	                 <script charset='utf-8' src='{0}/lang/zh_CN.js'></script>
                     <script> var editor_list=  new Array();
                              function getHtmlValue() {{
	                              // 同步数据后可以直接取得textarea的value
                                    for(var i = 0;i < editor_list.length; i++) {{
                                        editor_list[i].sync();
                                    }}
	                          }}
                              function resetHtmlValue() {{
	                              // 同步数据后可以直接取得textarea的value
                                    for(var i = 0;i < editor_list.length; i++) {{
                                        editor_list[i].html('');
                                    }}
	                              
	                          }}
                     </script>", model.UrLstr) ;
        }


        /// <summary>
        /// 创建fineuiPro的kindeditor代码
        /// </summary>
        /// <returns></returns>
        public string CreatKindByJquery()
        {
            //注意：由于有边框5，所以高度要减少5
            string js = string.Format(@" 
<script>
	$(function () {{
            var editorid_{0} = '{0}';
	        var  editor_{0} = KindEditor.create('textarea#' + editorid_{0}, {{
                width: '100%',
                height: $('#'+editorid_{0}).height-5,
                resizeType:0,
	            items : [{1}],
	            uploadJson: '{2}/asp.net/upload_json.ashx',
	          
	            {3}  
          
	        }});
	        {4}
	     
            editor_list[editor_list.length]=editor_{0};
     }});
</script>	                             ",
                model.EditorId, GetEditorType(model.EditorType), model.UrLstr, GetAllStr(),
                model.ReadOnly ? "editor_{0}.readonly(true);" : string.Empty) ;

            return js ;
        }

        /// <summary>
        /// 创建fineuiPro的kindeditor代码
        /// </summary>
        /// <returns></returns>
        public string CreatKindByFineui()
        {
            //注意：由于有边框5，所以高度要减少5
            string js = string.Format(@" 
<script>
	F.ready(function () {{
            var editorid_{0} = '{0}';
	        var  editor_{0} = KindEditor.create('textarea#' + editorid_{0}+'-inputEl', {{
                width: '100%',
                height: F(editorid_{0}).height-5,
                resizeType:0,
	            items : [{1}],
	            uploadJson: '{2}/asp.net/upload_json.ashx',
	            fileManagerJson: '{2}/asp.net/file_manager_json.ashx',     
	            {3}  
          
	        }});
	        {4}
	     
            editor_list[editor_list.length]=editor_{0};
     }});
</script>	                             ",
                model.EditorId, GetEditorType(model.EditorType), model.UrLstr, GetAllStr(),
                model.ReadOnly ? "editor_{0}.readonly(true);" : string.Empty) ;

            return js ;
        }

        private string GetAllStr()
        {
            string allowFileManagerStr = model.AllowFileManager ? "allowFileManager: true," : string.Empty ;
            string allowImageUploadStr = model.AllowImageUpload ? string.Empty : "allowImageUpload:false," ;
            string allowFlashUploadStr = model.AllowFlashUpload ? string.Empty : "allowFlashUpload:false," ;
            string allowMediaUploadStr = model.AllowMediaUpload ? string.Empty : "allowMediaUpload:false," ;
            string allowFileUploadStr = model.AllowFileUpload ? string.Empty : "allowFileUpload:false," ;
            string allStr = GetDeliveryLanguage(model.LanguageType) +
                            allowFileManagerStr +
                            allowImageUploadStr +
                            allowFlashUploadStr +
                            allowMediaUploadStr +
                            allowFileUploadStr ;

            return allStr ;
        }

        /// <summary>
        /// 获取国际化
        /// </summary>
        /// <param name="delivery"> 国际化名称</param>
        /// <returns></returns>
        private string GetDeliveryLanguage(KindeditorModel.LanguageMode delivery)
        {
            switch (delivery)
            {
                default:
                    return string.Empty ; //默认简体中文
                case KindeditorModel.LanguageMode.English:
                    return "langType:'en'," ;
                case KindeditorModel.LanguageMode.繁體中文:
                    return "langType:'zh_TW'," ;
                case KindeditorModel.LanguageMode.Korean:
                    return "langType:'ko'" ;
                case KindeditorModel.LanguageMode.Arabic:
                    return "langType:'ar'," ;
            }
        }

        private string GetEditorType(KindeditorModel.EditorMode mode)
        {
            switch (mode)
            {
                case KindeditorModel.EditorMode.普通:
                    return @"'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor',  'bold', 'italic', 'underline',
                                'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright',
                               '|', 'emoticons', 'image', 'link', 'fullscreen'" ;


                case KindeditorModel.EditorMode.仅表情:
                    return @"'emoticons'" ;

                default: //默认高级
                    //case KindeditorModel.EditorMode.高级:
                    return
                        @" 'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste',
		                     'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
		                     'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
		                     'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',
		                     'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
		                     'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image', 'multiimage',
		                     'flash', 'media', 'insertfile', 'table', 'hr', 'emoticons', 'baidumap', 'pagebreak',
		                     'anchor', 'link', 'unlink'" ; //, '|', 'about'  //去掉关于编辑器说明
                //AllowFileManager = true;


                case KindeditorModel.EditorMode.文本:
                    return @"'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
                             'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright','link', 'fullscreen'" ;


                case KindeditorModel.EditorMode.视频:
                    return @" 'media'" ;

                case KindeditorModel.EditorMode.上传图片:
                    return @" 'justifyleft', 'justifycenter', 'justifyright','image', 'multiimage'";
                //AllowMediaUpload = false;
            }
        }        

        /// <summary>
        /// 过滤flash标签为video标签，可以在线播放mp4等视频文件
        /// </summary>
        /// <param name="html"></param>
        /// <remarks>在显示内容时候调用此方法,例如: ViewBag.NewContent =KindeditorHelper.GetVideoHtml(model.NewContent)
        /// </remarks>
        /// <returns></returns>
        public static string GetVideoHtml(string html)
        {
            return html.Replace("<embed ", "<video controls ");
        }

    }

    public class KindeditorModel
    {
        private string _editorId = "kindeditor" ;

        /// <summary>
        /// 控件id名称
        /// </summary>
        public string EditorId
        {
            get { return _editorId ; }
            set { _editorId = value ; }
        }



        /// <summary>
        /// 语言类型
        /// </summary>
        public enum LanguageMode
        {
            English,
            简体中文,
            繁體中文,
            Korean,
            Arabic
        }

        /// <summary>
        /// 默认语言
        /// </summary>
        public LanguageMode _language = LanguageMode.简体中文 ;

        /// <summary>
        /// 国际化
        /// </summary>
        public LanguageMode LanguageType
        {
            get { return _language ; }
            set { _language = value ; }
        }

        /// <summary>
        /// 控件模式枚举
        /// </summary>
        public enum EditorMode
        {
            仅表情,
            高级,
            普通,
            文本,
            视频, 
            上传图片
        }

        /// <summary>
        /// 默认模式
        /// </summary>
        private EditorMode mode = EditorMode.高级 ;



        /// <summary>
        /// 控件模式
        /// </summary>
        public EditorMode EditorType { get ; set ; }

        #region 控件属性


        /// <summary>
        /// 路径(默认为../kindeditor),只设置一次就可以。
        /// </summary>
        public string UrLstr
        {
            get { return _Url ; }
            set { _Url = value ; }
        }

        private string _Url = "../kindeditor" ;

        /// <summary>
        /// true为只读模式
        /// </summary>
        public bool ReadOnly { get ; set ; }


        /// <summary>
        /// 是否可以浏览服务器文件(浏览图片，视频等文件)
        /// </summary>
        public bool AllowFileManager { get ; set ; }


        /// <summary>
        /// true时显示图片上传按钮。
        /// </summary>
        public bool AllowImageUpload { get ; set ; }

        /// <summary>
        /// true时显示Flash上传按钮。
        /// </summary>
        public bool AllowFlashUpload { get ; set ; }

        /// <summary>
        /// true时显示视音频上传按钮。
        /// </summary>
        public bool AllowMediaUpload { get ; set ; }

        /// <summary>
        /// true时显示文件上传按钮。
        /// </summary>
        public bool AllowFileUpload { get ; set ; }

        #endregion
    }
}

//注意！！button提交时候要先执行同步内容方法 OnClientClick="getHtmlValue()" （mvc类似），否则后台获取不到值。

/* webform 调用方式

 <%
    KindeditorModel kmo_NewContent = new KindeditorModel();
    kmo_NewContent.EditorType = KindeditorModel.EditorMode.高级;
    kmo_NewContent.UrLstr = "/AdminManager/res/kindeditor";
    kmo_NewContent.EditorId = kindeditor_NewContent.ClientID;//webform控件id
    kmo_NewContent.AllowFileManager = true;
    kmo_NewContent.AllowFileUpload = true;
    kmo_NewContent.AllowFlashUpload = true;
    kmo_NewContent.AllowImageUpload = true;
    kmo_NewContent.AllowMediaUpload = true;
    KindeditorHelper kh_NewContent = new KindeditorHelper(kmo_NewContent);
%>
<%=kh_NewContent .GetLoadJs() %>
<%=kh_NewContent.CreatKindByJquery()%>  

 */

/* mvc 调用方法：
  @Html.Raw(kindeditor.GetLoadJs())
 //创建kindeditor
  @Html.Raw(kindeditor.CreatKind());
 */
